import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

import qs from 'qs'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { useTagsViewStore } from '@/store/modules/tagsView'
import router,{ resetRouter } from '@/router'


import { config } from './config'

import { ElMessage, ElLoading } from 'element-plus'


const { result_code, base_url } = config
const appStore = useAppStore()
const { wsCache } = useCache()
const tagsViewStore = useTagsViewStore()



export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH]
let LoadingInstance
// 创建axios实例
const service:
  | AxiosInstance
  | {
      isShowErr: boolean | undefined //是否提示error
      isShowLoading: boolean | undefined //是否显示loading
      lableLoading: string | undefined //loading文本
    } = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
   
    if (
      config.method === 'post' &&
      (config.headers as AxiosRequestHeaders)['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }
    const token = wsCache.get(appStore.getUserInfo);
    console.log(token)
    if(token){
      
      (config.headers as AxiosRequestHeaders)['Authorization'] = token
    }
    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    // console.log(config, 'config')
    //是否显示loading
    if (config.isShowLoading === true) {
      LoadingInstance = ElLoading.service({
        target: document.querySelector('#app-wrap'),
        fullscreen: false,
        text: config.lableLoading || '加载中....'
      })
    }
    return config
  },
  (error: AxiosError) => {
    LoadingInstance&&LoadingInstance.close()
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    //hake
    if (response.data && response.data.code === undefined) {
      response.data.data = JSON.parse(JSON.stringify(response.data))
      response.data.code = result_code
    }
    if (response.config.isShowLoading === true) {
      LoadingInstance&&LoadingInstance.close()
    }
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.data && response.data.code === result_code) {
      return response.data
    }else if (response.data && response.data.code === 401) {

      wsCache.clear()
      tagsViewStore.delAllViews()
      console.log(router,'resetRouter................................')
      resetRouter() // 重置静态路由表
      router.push({name:'Login'})
    }  else {
      if (response.data) {
        if (response.config.isShowErr !== false) {
          ElMessage.error(response.data.message)
        }
        return Promise.reject(response)
      }
    }
  },
  (error: AxiosError) => {
    console.log(error, 'http err......') // for debug
    LoadingInstance&&LoadingInstance.close()
    ElMessage.error('网络错误')
    return Promise.reject(error)
  }
)

export { service }
